package com.xr.blackhoole.mock.section;

import com.xr.blackhoole.mock.WormholeMockCallback;
import com.xr.blackhoole.mock.annotation.WormholeMock;
import com.xr.blackhoole.mock.utils.WormholeMockUtils;
import com.xr.blackhoole.mvc.context.BlackholeContext;
import com.xr.blackhoole.mvc.context.BlackholeContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class WormholeMockSection {

    /**
     * 切点 拦截@WormholeMock的注解
     */
    @Pointcut("@annotation(com.xr.blackhoole.mock.annotation.WormholeMock)")
    public void pointCut() {
    }

    /**
     * 环绕通知
     *
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("pointCut()")
    public Object section(ProceedingJoinPoint point) throws Throwable {
        BlackholeContext wormholeContext = BlackholeContextHolder.getContext();
        Object[] parameter = point.getArgs();
        //如果没有wormholeContext 就执行正常方法
        if (null == wormholeContext) {
            return point.proceed(parameter);
        }
        //如果存在就执行MOCK方法
        WormholeMock wormholeMock = WormholeMockUtils.getMethodAnnotation(point, WormholeMock.class);
        if (null != wormholeMock) {
            //获取到 Mock 回调类
            WormholeMockCallback wormholeMockCallback =
                    WormholeMockUtils.getWormholeMockCallback(wormholeMock);
            if (null != wormholeMockCallback) {
                return wormholeMockCallback.handelMockData(parameter);
            }
        }
        return null;
    }

}
